import axios from "axios"
import { useData, useReqIp } from '@sker/runtime'
import { HttpError, md5, toFail, toSuccess, useEntityManager } from "@sker/core";
import { SysAddon } from "@sker/entities";
import { z } from 'zod'
export default async () => {
    const input = z.object({
        address: z.string()
    })
    const body = input.parse(useData())
    return useEntityManager(async m => {
        const addon = await m.findOne(SysAddon, { where: { name: '@imeepos/tmap' } })
        if (!addon) {
            throw new HttpError(`请安装腾讯地图应用`)
        }
        const setting = addon.setting;
        if (!setting) {
            throw new HttpError(`未找到相关配置`)
        }
        const key = setting.key;
        const sk = setting.secret;
        const params: any = {
            key,
            address: body.address
        }
        const paramsStr = Object.keys(params).sort().map(k => `${k}=${params[k]}`).join('&')
        const sig = md5(`/ws/smart_address/abnormal_analy?${paramsStr}${sk}`)
        const data = await axios.get(`https://apis.map.qq.com/ws/smart_address/abnormal_analy?${paramsStr}&sig=${sig}`).then(res => res.data)
        if (data) {
            if (data.status === 0) {
                return { data: data.data, count: data.count }
            }
            throw new HttpError(data.message)
        }
        throw new HttpError(`未知错误`)
    })

}
